﻿using Iorz.DomainSearch.Utils.Tools;

namespace Iorz.DomainSearch.Utils.Provider
{
    public class BaiduProvider : IProvider
    {
        private Cookies mCookies = new Cookies();

        private string mLog = "Error_Baidu.log";

        public string GetName()
        {
            return "百度云域名";
        }

        public bool Search(string domain, out bool isAvail)
        {
            isAvail = false;
            var response = HttpHelper.GetHtml(new HttpHelper.HttpRequest()
            {
                UserAgent = "Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
                Accept = "application/json, text/javascript, */*; q=0.01",
                ContentType = "application/json",
                Method = HttpHelper.HttpMethod.POST,
                KeepAlive = true,
                Url = GetBaiduyunUrl(),
                Referer = $"https://cloud.baidu.com/product/bcd/search.html?keyword={domain}",
                Cookies = GetCookies(),
                Postdata = "{\"type\":\"\",\"mode\":\"QUICK\",\"keyword\":\"" + domain + "\"}"
            });

            if (response.Exception == null
                && !string.IsNullOrEmpty(response.Html)
                && response.Html.IndexOf("\"success\":\"true\"") != -1)
            {
                if (response.Html.IndexOf("\"status\":\"UNREGISTERED\"") != -1)
                {
                    Tracker.Log("domain.log", domain);
                    isAvail = true;
                }

                return true;
            }

            if (response.Exception == null)
                Tracker.Log(mLog, response.Html);
            else
                Tracker.Log(mLog, response.Exception.Message);

            return false;
        }

        private static string GetBaiduyunUrl()
        {
            return $"https://cloud.baidu.com/api/bcd/order/search";
        }

        private string GetCookies()
        {
            var timespan = DateHelper.GetTimestamp4Second();
            mCookies.Update($"BAIDUID=A03EE137E2FDD4A58E1F81AB155CFF2E:FG=1; PSTM=1433496555; BIDUPSID=71617F6305CD8F9776FCEF7A8080C3D6; Hm_lvt_28a17f66627d87f1d046eae152a1c93d={timespan}; Hm_lpvt_28a17f66627d87f1d046eae152a1c93d={timespan}");
            return mCookies.ToString();
        }
    }
}
